﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SCM.Common;
using System.Linq;

namespace SCM.WebAPI.Filter
{
    /// <summary>
    /// 执行动作过滤器
    /// </summary>
    public class SCMActionFilter : IActionFilter
    {
        /// <summary>
        /// 执行后动作
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (!context.ModelState.IsValid)
            {
                ViewDataPack<string> result = new ViewDataPack<string>() { Code = Common.ResultCode.ParameterError };

                var errors = context.ModelState
                   .Where(e => e.Value.Errors.Count > 0)
                   .Select(e => e.Value.Errors.First().ErrorMessage)
                   .ToList();
                result.Message = string.Join("|", errors);
                context.Result = new JsonResult(result);
            }
        }

        /// <summary>
        /// 执行时动作
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context) { }
    }
}
